#include <iostream>
#include "Spriteset.hpp"


int main(int argc, char* argv[])
{
  if (argc != 4) {
    std::cout << "Syntax: import_art <art_file> <palette_file> <output_file>" << std::endl;
    return 1;
  }


  FILE* art_file = fopen(argv[1], "rb");
  if (art_file == NULL) {
    std::cout << "Could not open art file" << std::endl;
    return 1;
  }

  FILE* palette_file = fopen(argv[2], "rb");
  if (palette_file == NULL) {
    fclose(art_file);
    std::cout << "Could not open palette file" << std::endl;
    return 1;
  }

  sSpriteset spriteset;
  spriteset.Create(32, 4);
  spriteset.ResizeFrames(20, 20);


  // read palette
  RGB palette[256];
  fread(palette, 3, 256, palette_file);

  RGBA palette_rgba[256];
  for (int i = 0; i < 256; i++) {
    palette_rgba[i].red   = palette[i].red   * 4;
    palette_rgba[i].green = palette[i].green * 4;
    palette_rgba[i].blue  = palette[i].blue  * 4;
    palette_rgba[i].alpha = (i != 0) * 255;
  }


  for (int i = 0; i < 32; i++) {
    for (int j = 0; j < 4; j++) {
      for (int y = 0; y < 20; y++) {
        for (int x = 0; x < 20; x++) {
          byte color = fgetc(art_file);
          CImage32& image = spriteset.GetFrame(i, j);
          (image.GetPixels())[y * image.GetWidth() + x] = palette_rgba[color];
        }
      }
    }
  }


  if (spriteset.Save(argv[3])) {
    std::cout << "save successful" << std::endl;
  } else {
    std::cout << "save failed" << std::endl;
  }

  fclose(art_file);
  fclose(palette_file);
  return 0;
}
